import axios from "axios";
import { message } from "ant-design-vue";

let instance = axios.create({
  timeout: 60000,
});
instance.interceptors.request.use(
  (req) => {
    req.headers.Authorization = localStorage.getItem("token")
      ? `Bearer ${localStorage.getItem("token")}`
      : "";
    return req;
  },
  (err) => {
    return Promise.reject(err);
  }
);
instance.interceptors.response.use(
  (res) => {
    handleResponseError(res);
    if (res.status == 200) {
      if (res.data.success || res.data.code == 100) {
        if (res.data.showMessage) {
          message.success(res.data.message);
        }
        return Promise.resolve(res.data);
      }
    } else {
      return Promise.reject(res.data);
    }
  },
  (err) => {
    handleResponseError(err.response);
    return Promise.reject(err.response);
  }
);

function handleResponseError(err) {
  let status;
  if (err && err.status) {
    status = err.status;
  }
  switch (status) {
    case 403:
      if (err.data.showMessage) {
        message.error(err.data.message);
      }
      if (!err.data.success) {
        setTimeout(() => {
          top.location.href = "./login.html";
        }, 1000);
      }
      break;
    case 401:
      message.error("请求未授权,即将跳转到登录页!");
      if (!err.data.success) {
        setTimeout(() => {
          top.location.href = "./login.html";
        }, 1500);
      }
      break;
  }
}

export default instance;
